package com.tenement.controller.foreground.user;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tenement.base.constants.SysmConstants.existed;
import com.tenement.base.constants.SysmConstants.state;
import com.tenement.mybatis.entity.User;
import com.tenement.service.interfaces.IUserService;
import com.tenement.utils.base.StringRandom;

/**
 * 用户注册
 * 
 * @author wk
 *
 */
@Controller
public class UserRegisterController {

	private static final Log logger = LogFactory.getLog(UserRegisterController.class);

	@Autowired
	private IUserService iUserService;

	/**
	 * 进入用户登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user_register.action")
	public String toUserRegisterHtml() {
		logger.info("【-进入用户注册页面-】");
		return "redirect:view/foreground/user/user_register.html";
	}

	/**
	 * 校验用户手机号是否已经被占用,注册时候的验证,其他手机号是否存在验证需要传入用户id表示手机号与用户已经绑定了
	 * 
	 * @param phone
	 * @return
	 */
	@RequestMapping(value = "/verifyPhoneUsed.action")
	public @ResponseBody String verifyPhoneUsed(@RequestBody String phone) {
		logger.info("前台传来的phone【-" + phone + "-】");
		if (phone == null || "".equals(phone)) {
			try {
				throw new Exception("【-校验手机号是否已被占用，参数为空-】");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		boolean b = iUserService.verifyPhoneUsed(phone);
		if (b) {
			return existed.Yes;// 该手机号已存在
		} else {
			return existed.No;// 该手机号可以使用
		}
	}

	/**
	 * 用户注册数据提交
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/userRegister.action")
	public @ResponseBody String userRegister(@RequestBody String data) {
		JSONObject json = JSON.parseObject(data);
		String phone = json.getString("phone");
		String pwd = json.getString("pwd");
		String nickName = StringRandom.getStringRandom();// 生成随机的昵称
		logger.info("用户注册传来的数据【-" + phone + "-】" + "【-" + pwd + "-】");
		boolean b = iUserService.userReister(new User(phone, pwd, nickName));
		if (b) {
			return state.Success;
		} else {
			return state.Failed;
		}
	}

}
